package com.alogic.xscript.plugins;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

import java.math.BigInteger;

/**
 * 将long变量转化为hex形式输出
 */
public class Hex extends AbstractLogiclet {
    protected String id;
    protected String $value;
    protected boolean ref = false;

    public Hex(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);
        id = PropertiesConstants.getString(p,"id","$" + this.getXmlTag(),true);
        $value = PropertiesConstants.getRaw(p,"value","");
        ref = PropertiesConstants.getBoolean(p,"ref",false,true);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, final LogicletContext ctx, final ExecuteWatcher watcher){
        String value = PropertiesConstants.transform(ctx,$value,"");
        if (StringUtils.isNotEmpty(value)) {
            long longValue = ref?PropertiesConstants.getLong(ctx,value,-1):getLong(value,-1);
            if (longValue > 0) {
                ctx.SetValue(id, Long.toHexString(longValue));
            }
        }
    }

    protected long getLong(String v,long dft){
        try{
            return Long.parseLong(v);
        }catch (NumberFormatException ex){
            ex.printStackTrace();
            return dft;
        }
    }
}